const IROWCOUNT = 8;
const IROWDIS = 65;
var undoMgr = require("MoveMgr");

cc.Class({
    extends: cc.Component,

    properties: {
        textStep: cc.Label,
        textTime: cc.Label,
        goCard: cc.Node,
        goFind: cc.Node,
        goMove: cc.Node,
        goChoice: cc.Node,
    },

    // use this for initialization
    onLoad: function () {
        
    },

    start: function(){
        this.initParas ();
        this.initShow ();
        var self = this;
        this.textTime.scheduleOnce(function (argument) {
            self.onClickStart();
        }, 1);
    },

    // called every frame
    update: function (dt) {
        
    },

    initParas: function(){
        this.lCards = [];
        this.lFindCards = [];
        this.lCardDatas = [];

        this._gameCount = 0;
        this._bTouch = true;
        this._bShowBtns = true;
        this._bPlayCard = false;
        
        undoMgr.init(this);
        this.adMgr = cc.find("Mgr").getComponent("AudioMgr");
        this.tTrans = [cc.find ("Kdjl/ndH"), cc.find ("Kdjl/ndLeft"), cc.find ("Kdjl/ndRight")];
        this.reset ();
    },

    initShow: function(){
        this.initBtnEvents ();
        this.initGoCards ();
    },

    getPLX: function(){
        return _plx;
    },

    reset: function(){
        this._iPrompt = 0;
        this._bWin = false;
        this._iStep = 0;
        this.showTextStep (this._iStep);
        this._iTime = 0;
        this.textTime.string = "00:00";
        undoMgr.removeAll ();
        // redoMgr.removeAll ();
    },

    initBtnEvents: function(){
        var tNode = cc.find("Kdjl/ndBtns").children;
        tNode[0].on("click", this.onClickStart, this);
        // tNode[1].on("click", this.onClickAuto, this);
        tNode[2].on("click", this.onClickUndo, this);

        // this._iDiff = 1;
        this._iDiff = 3;
        var lLab = [];
        var self = this;
        var children = cc.find("Kdjl/goToggles").children;
        for (var i = 0; i < 3; i++){
            var trans = children[i];
            trans.setTag(i);
            lLab.push(trans.children[2]);
            
            trans.on("toggle", function (event) {
                var tog = event.detail;
                self.adMgr.PlaySound ("click");
                lLab[self._iDiff - 1].color = cc.Color.WHITE;
                var idx = tog.node.getTag();
                self._iDiff = idx + 1;
                lLab[idx].color = new cc.Color(0, 255, 255);
            }, this);
        }

        self._bShowBtns = true;
        var btnShow = cc.find("Kdjl/btnShow");
        btnShow.on("click", function (argument) {
            self._bShowBtns = !self._bShowBtns;
            var bShow = self._bShowBtns;
            cc.find("Kdjl/ndBtns").active = bShow;
            cc.find("Kdjl/goToggles").active = bShow;
            btnShow.children[0].getComponent(cc.Label).string = bShow == true ? "隐藏" : "显示";
        }, this);
    },

    onClickStart: function() {
        if (this._bPlayCard == true)
            return;
        // setTouchable (false);
        for (var i = 0, iLen = this.lCards.length; i < iLen; i++) {
            var card = this.lCards[i];
            card.node.active = false;
            card.node.parent = this.goMove;
        };
        if (this._iDiff == 3)
            this.initDataCardsDiff ();
        else
            this.initDataCards ();
        this.reset ();
        if (this.coPlayTime != null)
            this.textTime.unschedule(this.coPlayTime);
        // StartCoroutine (playCards());
        this.playCards();

        this._gameCount++;
        this.adMgr.PlaySound ("start");
    },

    onClickUndo: function(){
        if (this._iStep == 0 || this._bWin == true)
            return;
        this.showTextStep (--this._iStep);
        // redoMgr.addCard (undoMgr);
        undoMgr.onMoveCard();
    },

    onClickAuto: function(){
        if (this._bWin == true)
            return;
        this.playAutoMoveCards();
    },

    playTextTime(){
        var self = this;
        this.coPlayTime = function(){
            self.textTime.string = self.getStrTime (++self._iTime);
            if (self._iTime > 3600){
                self.adMgr.PlaySound ("lose");
                self.textTime.unschedule(self.coPlayTime);
                self.textTime.scheduleOnce(function (argument) {
                    self.onClickStart();
                }, 2);
            }
        }
        this.textTime.schedule(this.coPlayTime, 1);
    },

    getStrTime(iTime){
        var str = "";
        var time = [];
        time[0] = Math.floor(iTime / 60);
        time[1] = iTime % 60;
        var v;
        for (var i = 0; i < time.length; i++) {
            v = time [i];
            if (v < 10)
                str += "0" + v.toString();
            else
                str += v.toString();
            if (i == 0)
                str += ":";
        }
        return str;
    },

    showTextStep(iStep){
        this.textStep.string = iStep;
    },

    initGoCards: function() {
        this.goCard.active = false;
        for (var i = 0; i < 52; i++){
            var item;
            if (i == 0)
                item = this.goCard;
            else {
                var goCardTemp = cc.instantiate(this.goCard);
                goCardTemp.parent = this.goMove;
                // goCardTemp.transform.localScale = Vector3.one;
                item = goCardTemp;
            }
            var card = item.getComponent("Card");
            this.lCards.push(card);
        }
    },

    initDataCards: function() {
        var cardSp1 = [
            101, 102, 103,
            201, 202, 203,
            301, 302, 303,
            401, 402, 403,
        ];
        var cardSp2 = [
            101,
            201,
            301,
            401,
        ];
        var cardInit = this._iDiff == 1 ? cardSp1 : cardSp2;
        var len = 52;
        var iCount = cardInit.length / 4;
        for (var i = 0; i < 4; i++) {
            for (var j = 0; j < iCount; j++) {
                var idx = j + iCount * i;
                var iCard = cardInit [idx];
                var iCardNum = iCard % 100;
                var iCardType = Math.floor (iCard / 100);
                var card = this.lCards [len - idx - 1];
                card.init (iCardNum, iCardType, 2, i, this);
                card.node.parent = this.getTransP (2, i);
                card.node.setPosition(0, 0);
                // card.Node.localPosition
            }
        }
        var CARDS1 = [
            104, 105, 106, 107, 108, 109, 110, 111, 112, 113,
            204, 205, 206, 207, 208, 209, 210, 211, 212, 213,
            304, 305, 306, 307, 308, 309, 310, 311, 312, 313,
            404, 405, 406, 407, 408, 409, 410, 411, 412, 413,
        ];
        var CARDS2 = [
            102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113,
            202, 203, 204, 205, 206, 207, 208, 209, 210, 211, 212, 213,
            302, 303, 304, 305, 306, 307, 308, 309, 310, 311, 312, 313,
            402, 403, 404, 405, 406, 407, 408, 409, 410, 411, 412, 413,
        ];
        var CARDS = this._iDiff == 1 ? CARDS1 : CARDS2;
        this.lCardDatas = [];
        while (true) {
            var iRandom = Math.floor(Math.random() * (CARDS.length - 1));
            var iCard = CARDS.splice(iRandom, 1);
            this.lCardDatas.push(iCard);
            if (CARDS.length == 0) break;
        };
    },

    initDataCardsDiff: function() {
        var CARDS = [
            101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113,
            201, 202, 203, 204, 205, 206, 207, 208, 209, 210, 211, 212, 213,
            301, 302, 303, 304, 305, 306, 307, 308, 309, 310, 311, 312, 313,
            401, 402, 403, 404, 405, 406, 407, 408, 409, 410, 411, 412, 413,
        ];
        this.lCardDatas = [];
        while (true) {
            var iRandom = Math.floor(Math.random() * (CARDS.length - 1));
            // if (_gameCount % 3 == 1)
            //     iRandom = CARDS.length - 1;
            var iCard = CARDS.splice(iRandom, 1);
            this.lCardDatas.push(iCard);
            if (CARDS.length == 0) break;
        };
    },

    playCards: function() {
        var len = this.lCardDatas.length;
        var self = this;
        var i = 0;
        this._bPlayCard = true;
        this.textTime.schedule(function (argument) {
            for (var j = 0; j < IROWCOUNT; j++) {
                var idx = j + IROWCOUNT * i;
                if (idx >= len)
                    break;
                var iCard = self.lCardDatas [idx];
                var iCardNum = iCard % 100;
                var iCardType = Math.floor (iCard / 100);
                var card = self.lCards [idx];
                card.init (iCardNum, iCardType, 0, j, self);

                var parent = self.getTransP(0, j);
                card.node.parent = parent;
                card.node.setPosition(0, 0 - 30 * i);
            }
            i++;
            if (i >= 7){
                self._bPlayCard = false;
                self.setBMove ();
                self.playTextTime();
            }
        }, 0.2, 6, 0);
        // yield return new WaitForSeconds (0.5f);
        // setTouchable (true);
    },

    setBMove: function(){
        var preCard = null;
        for (var i = 0; i < IROWCOUNT; i++){
            var trans = this.getTransP(0, i);
            var children = trans.children;
            var len = children.length - 1;
            if (len < 0)
                continue;
            for (var j = len; j >= 0; j--) {
                var card = children[j].getComponent("Card");
                if ((j == len) || (preCard.getBMove () == true && card.getColor () != preCard.getColor () && card.getCardNum () - 1 == preCard.getCardNum ()))
                    card.setBMove (true);
                else{
                    card.setBMove (false);
                }
                preCard = card;
            }
        }
    },

    getBDropped: function(card, touch){
        for (var i = 0; i < this.tTrans.length; i++) {
            var trans = this.tTrans [i];
            var children = trans.children;
            for (var j = 0; j < trans.childrenCount; j++) {
                var rect = children[j];
                var rChilds = rect.children;
                if (i == 0 && rect.childrenCount > 0)
                    rect = rChilds[rect.childrenCount - 1];
                var newVec2 = rect.convertTouchToNodeSpace(touch);
                if (newVec2.x >= 0 && newVec2.x <= 60 && newVec2.y >= 0 && newVec2.y <= 80){
                    if (card.getPos() == i && card.getRow() == j) return false;
                    if (i == 0) 
                        return this.getBSuitCard (card, j);
                    else if (card.getItems().length == 0) {
                        if (i == 1 && rect.childrenCount == 0) {
                            this.onCardMove (card, i, j);
                            return true;
                        }
                        if (i == 2 && this.getBMoveToDes (card, j) == true) {
                            return true;
                        }
                        return false;
                    }
                    else 
                        return false;
                }
            }
        }

        return false;
    },

    onDrop(card){
        this.showTextStep (++this._iStep);
        undoMgr.addCard(card);
        // redoMgr.removeAll ();
    },

    onCardMove: function(card, iPos, iRow){
        this.onDrop (card);
        this.moveCards (card, iPos, iRow);
    },

    moveCards: function(card, iPos, iRow){
        this.adMgr.PlaySound ("move");
        var bAutoMove = false;
        // if (card.node.parent == this.goMove) {
        //     bAutoMove = false;
        // }
        // if (bAutoMove == true && iPos == 0)
        //     card.addItems ();
        var items = card.getItems ();
        var trans = this.getTransP(iPos, iRow);
        card.setPos (iPos);
        card.setRow (iRow);
        card.node.parent = trans;
        if (iPos != 0) {
            this.setBMove ();
            this.showWin ();
            if (bAutoMove == false) {
                card.node.setPosition(0, 0);
                // var rect = card.gameObject.GetComponent<RectTransform> ();
                // rect.anchoredPosition = new Vector2 (rect.rect.width / 2, -rect.rect.height / 2);
            } else {
                // card.transform.SetParent (goMove.transform);
                // var px = iPos == 1 ? (_plx + 65 * iRow) : (_prx - 65 * iRow);
                // var pos = card.gameObject.GetComponent<RectTransform> ().anchoredPosition;
                // card.showMove (px - pos.x, _ply - pos.y, px);
            }
        } else if (iPos == 0){
            if (items.length > 0) {
                for (var i = 0; i < items.length; i++) {
                    var cCard = items[i].getComponent("Card");
                    cCard.setPos (iPos);
                    cCard.setRow (iRow);
                    items[i].parent = trans;
                };
            }
            this.setBMove ();
            if (bAutoMove == false) {
                card.node.setPosition(0, 0 - 30 * (trans.childrenCount - 1 - items.length));
                if (items.length > 0) {
                    var idx = 0;
                    for (var i = 0; i < items.length; i++) {
                        idx++;
                        items[i].setPosition(0, 0 - 30*(trans.childrenCount - 1 + idx - items.length));
                    };
                }
            } else {
            }
        }
    },

    getBSuitCard: function(cardDown, iRow){
        var iPos = 0;
        var rect = this.getTransP(iPos, iRow);
        if (rect.childrenCount == 0) {
            this.onCardMove (cardDown, iPos, iRow);
            return true;
        } else {
            var cardUp = rect.children[rect.childrenCount - 1].getComponent("Card");
            if (cardDown.getColor () != cardUp.getColor () && cardUp.getCardNum () - cardDown.getCardNum () == 1) {
                this.onCardMove (cardDown, iPos, iRow);
                return true;
            }
        }
        return false;
    },

    getBMoveToMedium(card){
        var iPos = 1;
        var trans = this.tTrans [iPos];
        var children = trans.children;
        for (var i = 0; i < trans.childrenCount; i++) {
            var transTemp = children[i];
            if (transTemp.childrenCount == 0) {
                this.onCardMove (card, iPos, i);
                return true;
            }
        }
        return false;
    },

    getBMoveToTotalDes: function(card){
        for (var i = 0; i < this.tTrans[2].childrenCount; i++) {
            if (this.getBMoveToDes (card, i) == true) {
                return true;
            }
        }
        return false;
    },

    getBMoveToDes: function(card, iRow) {
        var transTemp = this.getTransP(2, iRow);
        if (card.getCardType () - 1 == iRow) {
            var iLen = transTemp.childrenCount;
            if ((iLen == 1 && card.getCardNum () == 1) ||
                (iLen > 1 && card.getCardNum () - 1 == transTemp.children[iLen - 1].getComponent("Card").getCardNum ())) {
                this.onCardMove (card, 2, iRow);
                return true;
            }
        }
        return false;
    },

    getBMoveToCard (card, bMove) {
        var iPos = 0;
        var transP = this.tTrans [iPos];
        var children = transP.children;
        for (var i = 0; i < transP.childrenCount; i++) {
            if (card.getPos() == 0 && card.getRow() == i) continue;
            var rect = children[i];
            if (rect.childrenCount > 0) {
                var cardUp = rect.children[rect.childrenCount - 1].getComponent("Card");
                if (card.getColor () != cardUp.getColor () && cardUp.getCardNum () - card.getCardNum () == 1) {
                    if (bMove == true)
                        this.onCardMove (card, iPos, i);
                    return true;
                }
            }
        }
        for (var i = 0; i < transP.childrenCount; i++) {
            if (card.getPos() == 0 && card.getRow() == i) continue;
            if (children[i].childrenCount == 0) {
                if (bMove == true)
                    this.onCardMove (card, iPos, i);
                return true;
            }
        }
        return false;
    },

    getTransP: function(iPos, iRow){
        return this.tTrans [iPos].children[iRow];
    },

    showWin: function(){
        var iPos = 2;
        var trans = this.tTrans [iPos];
        var bWin = true;
        var children = trans.children;
        for (var i = 0; i < trans.childrenCount; i++) {
            var transTemp = children[i];
            if (transTemp.childrenCount != 14) {
                bWin = false;
                break;
            }
        }
        if (bWin == true) {
            this._bWin = true;
            // setTouchable (false);
            this.adMgr.PlaySound ("win");
            // StopCoroutine (coPlayTime);
            // Invoke ("playWin", 2.0f);
        }
    },
});
